package org.core.tliaswebmanagement.exception;

import lombok.extern.slf4j.Slf4j;
import org.core.tliaswebmanagement.pojo.Result;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

//@RestControllerAdvice==@ControllerAdvice+@ResponseBody
@Slf4j
@RestControllerAdvice
public class GlobalExceptopnHandler {
    @ExceptionHandler
    public Result handleException(Exception e) {
        log.error("程序出错了: ", e);
        return Result.error("服务器出错了");
    }

    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        log.error("程序出错了: ", e);
        String message = e.getMessage();
        int index = message.indexOf("Duplicate entry");
        String errorMsg = message.substring(index);
        String[] arr = errorMsg.split(" ");
        return Result.error(arr[2]+"已存在");
    }
}
